package http;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import utils.Configure;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Map;

/**
 * 功能描述:
 *
 * @author liping(lpaidd50@gmail.com)
 * @version v1.0
 * @date 2016/8/10
 */
public class HttpRequest {
	CloseableHttpClient		httpclient		= null;
	
	//表示请求器是否已经做了初始化工作
	private boolean			hasInit			= false;
	
	//连接超时时间，默认10秒
	private int				socketTimeout	= 10000;
	
	//传输超时时间，默认30秒
	private int				connectTimeout	= 30000;
	
	//请求器的配置
	private RequestConfig	requestConfig;
	
	public HttpRequest(String keyPath, String pwd) throws Exception {
		init(keyPath, pwd);
	}
	
	public void init(String keyPath, String pwd) throws Exception {
		
		KeyStore trustStore = KeyStore.getInstance("PKCS12");
		if (keyPath != null && !"".equals(keyPath)) {
			URL url = new URL(keyPath);
			HttpURLConnection uc = (HttpURLConnection) url.openConnection();
			uc.connect();
			InputStream instream = uc.getInputStream();
			try {
				trustStore.load(instream, pwd.toCharArray());//设置证书密码
			} catch (CertificateException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} finally {
				instream.close();
			}
			
			// 相信自己的CA和所有自签名的证书
			SSLContext sslcontext = SSLContexts.custom()
				.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
			// 只允许使用TLSv1协议
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
				new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} else {
			httpclient = HttpClients.custom().build();
		}
		
		//根据默认超时限制初始化requestConfig
		requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
			.setConnectTimeout(connectTimeout).build();
		
		hasInit = true;
	}
	
	public Map<String, String> sendPost(String url, Map<String, String> params) {
		if (!hasInit)
			return null;
		HttpPost httpPost = new HttpPost(url);

		return null;
	}
}
